/**
 * 创建于：5/30/16
 * 创建人：qizhang
 * 说明：
 */
import React from 'react'
import BaseComponent from 'basecomponent'
import {withRouter} from 'react-router'
import Auth from '../../../auth'
import icons,{login} from 'icons'
import LoginInput from './logIn-input'
import './style.scss'
import Md5 from 'blueimp-md5'
import apis from 'apis'
import appConfig from '../../../config'

class Login extends BaseComponent {
  constructor() {
    super(...arguments);
    this.state = {
      sessionId:'',
      user: {
        val: '',
        isFocus: false
      },
      password: {
        val: '',
        isFocus: false
      },
      verify:{
        val:'',
        isFocus:false,
      },
      isLogining: false,

      isLoadingVPic:false,
      verifyPic:{},
    }
  }

  static getErrorMsgs(code) {
    let msgs = {
      "-3": "找不到此用户",
      "-4": "密码错误",
      "-5": "请输入用户名或登录密码",
      "-7": "用户没有登录该客户端的权限"
    }
    return msgs[code]
  }

  /* static setCookie(name,value,time){
         let d = new Date();
         d.setTime(d.getTime() + ((time || 30)*24*60*60*1000));
         let expires = "expires="+d.toUTCString();
         document.cookie = name+"="+value+';'+expires;

     }
     static getCookie(name){

     }
     static clearCookie(name){
         setCookie(name, "", -1);
     }*/

  submit() {
    let {user, password, isLogining} = this.state;
    let hash = Md5(`${password.val}`);
    this.setState({isLogining: true}, () => {
      Auth.authorize(user.val, hash, (err, data) => {
        if (err) {
          console.log(err)
          this.setState({isLogining: false})
          let msg = Login.getErrorMsgs(err.code);
          let info = '';
          msg ? info = msg : info = err.msg;
          return alert(info);
        }
        this.props.router.replace('home');
      });
    })
  }

  componentDidMount() {
    this.initVerifyCode();
    document.onkeydown = (event) => {
      let e = event || window.event || arguments.callee.caller.arguments[0];
      //enter
      if (e && e.keyCode == 13) {
        this.submit();
      }
    };
  }

  initVerifyCode(){
    this.initRP&& this.initRP.request.abort();
    this.initRP = apis.verify.initVerify();
    this.registerRequest(this.initRP.request);
    this.initRP.promise.then((res)=>{
      res.Data && this.setState({sessionId:res.Data.sessionId})
    })
      .catch((err)=>{
        console.log(msg)
        alert(err.msg)
    })
  }

  loadVerifyPic(isFocus){
    const {user,sessionId} = this.state;
    if(!isFocus && user && user.val.length > 0){
      this.setState({verifyPic:`${appConfig.apiHost}/Account/Vfy/GetGph?username=${user.val}&sessionId=${sessionId}`});
      //图片流我居然去处理了，而且还有问题。。。
      /*let self = this;
      let url = `${appConfig.apiHost}/Account/Vfy/GetGph?username=${user.val}&sessionId=${sessionId}`;
      let xhr = new XMLHttpRequest();
      xhr.open('GET',url,true);
      xhr.setRequestHeader('Authorization',auth.getToken() ? `CAuth ${auth.getToken()}` : '');
      xhr.onload = function () {
        if(this.status == 200){
          // let blob = this.response;
          let binaryData = [];
          binaryData.push(this.response);
          let src = window.URL.createObjectURL(new Blob(binaryData,{type:'image/bmp'}));
          self.setState({verifyPic:src})
        }
      };
      xhr.send();*/
    }
  }

  checkVerify(val){
    const{user,sessionId} = this.state;
    if(val && val.length>0){
      let postData={
        Username:user.val,
        LoginType:0,
        Type:2,
        Role:0,
        sessionId:sessionId,
        gphCode:val,
      }

      this.checkVRP&& this.checkVRP.request.abort();
      this.checkVRP = apis.verify.checkVerifyCode(postData);
      this.registerRequest(this.checkVRP.request);
      this.checkVRP.promise.then((res)=>{

      })
        .catch((err)=>{
          alert(err.msg)
        })
    }
  }

  render() {
    const {password, isLogining, user,verify,verifyPic} = this.state;
    return (
      <div className="login" style={{backgroundImage: `url(${login.background})`}}>
        <div className={'title-wrapper'}>
          <div className="image title" >
            <div className={'title-bg'}/>
            <div className={'title-bottom-bg'} style={{backgroundImage: `url(${login.logoUnder})`}}/>
          </div>
          <div className={'title-logo image'} style={{backgroundImage: `url(${icons.logo})`}}/>
          <div className={'title-name image'} style={{backgroundImage: `url(${icons.logoName})`}}/>
          <div className={'title-version'}>V1.0</div>
        </div>
        <div className="login-window">
            <div className="form">
              <LoginInput className="user"  val={user.val}
                          inputChange={(val) => this.setState({user: Object.assign({}, user, {val: val})})}
                          title="用户名" type="text" isFocus={user.isFocus}
                          changeIsFocus={(val) => {
                            this.setState({user: Object.assign({}, user, {isFocus: val})});
                            this.loadVerifyPic(val)
                          }}/>

              <LoginInput className="password"
                          val={password.val}
                          inputChange={(val) => this.setState({password: Object.assign({}, password, {val: val})})}
                          title="登录密码" type="password" isFocus={password.isFocus}
                          changeIsFocus={(val) => this.setState({password: Object.assign({}, password, {isFocus: val})})}/>

              <LoginInput className="verify" val={verify.val} imgSrc={verifyPic}
                          inputChange={(val) => {
                            this.checkVerify(val);
                            this.setState({verify: Object.assign({}, verify, {val: val})})
                          }}
                          title="验证码" type="text" isFocus={verify.isFocus}
                          changeIsFocus={(val) => this.setState({verify: Object.assign({}, verify, {isFocus: val})})}/>

              <button className="login-btn" onClick={() => {
                !isLogining && this.submit()
              }}>
                {isLogining ? '登录中' : '登录'}</button>
            </div>
        </div>
      </div>
    )
  }
}

Login.contextTypes = {
  router: React.PropTypes.object
};

module.exports = withRouter(Login);
